from flask import render_template, current_app, session, request, jsonify

from info.constants import HOME_PAGE_MAX_NEWS
from info.models import User, News, Category
from info.utils.response_code import RET, error_map
from . import home_blu


# 2使用蓝图来注册路由
@home_blu.route('/')
def index():
    # 查询根路由有无user_id--展示登陆界面
    user_id = session.get('user_id')
    user = None
    if user_id:
        # TODO user传入模板，后端渲染登录展示
        # 已经登录过了
        try:
            user = User.query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)
    #  将模型转换为字典
    user = user.to_dict() if user else None

    # TODO 展示新闻排行榜列表后端渲染
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10).all()
    except Exception as e:
        current_app.logger.error(e)
    # 将模型转换为字典
    news_list = (news.to_dict() for news in news_list)

    # 查询分类数据，加入添加分类或者别的
    categories = []
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)
    return render_template('news/index.html', user=user, news_list=news_list, categories=categories)


# 实现图标的路由
@home_blu.route('/favicon.ico')
def favicon():
    # 网站的小图标请求是浏览器自动发起的，只需要实现这个路由，并且返回图片即可
    # flask内置了获取静态文件的语法，send_static_file，flask访问静态文件的路由底层也是调用这个方法
    return current_app.send_static_file('news/favicon.ico')
    # return current_app.send_static_file('news/lkss.jpg')


# TODO 获取新闻列表，按照发布时间分类页码查询出来
# 请求参数－分类的id，当前的页码cur_page,每页条数per_count
@home_blu.route('/get_news_list')
def get_news_list():
    # 获取参数
    cid = request.args.get('cid')
    cur_page = request.args.get('cur_page')
    per_count = request.args.get('per_count', HOME_PAGE_MAX_NEWS)
    # 校验参数
    if not all([cid, cur_page]):
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])

    #  格式转换
    try:
        cid = int(cid)
        cur_page = int(cur_page)
        per_count = int(per_count)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg=error_map[RET.PARAMERR])
    filter_list = [News.status==0]
    if cid != 1:
        filter_list.append(News.category_id == cid)
    # 通过发布时间和分类
    try:
        pn = News.query.filter(*filter_list).order_by(News.create_time.desc()).paginate(cur_page, per_count)
        news_list = [news.to_dict() for news in pn.items]
        total_page = pn.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg=error_map[RET.DBERR])

    data = {
        "news_list": news_list,
        "total_page": total_page
    }
    # TODO 将新闻界面 data封装到json中返回
    return jsonify(errno=RET.OK, errmsg=error_map[RET.OK], data=data)
